package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.ex.BusinessException;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.query.EmployeeQueryObject;
import cn.wolfcode.rbac.service.IEmployeeServcie;
import cn.wolfcode.rbac.web.vo.EmployeeVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeServcie {
    @Autowired
    private EmployeeMapper employeeMapper;

    public PageInfo<Employee> selectList(EmployeeQueryObject qo) {
        // 启动分页插件
        PageHelper.startPage(qo.getPageNum(),qo.getPageSize());
        // 查询列表，然后封装到 PageInfo
        return new PageInfo<Employee>(employeeMapper.selectAll(qo));
    }

    @Override
    @Transactional
    public void add(EmployeeVo vo) {
        //1.进行合法性校验
        Employee employee = vo.getEmployee();
        if(employee==null){
            throw new BusinessException("非法参数");
        }
        //2.插入员工数据
        employeeMapper.insert(employee);
        //3.维护中间表的关系(插入)
        List<Long> roleIds = vo.getRoleIds();
        if(roleIds!=null && roleIds.size()>0){
            employeeMapper.insertRoleRelationBatch(employee.getId(),roleIds);
        }
    }

    @Override
    @Transactional
    public void update(Long id, EmployeeVo vo) {
        Employee employee = vo.getEmployee();
        if(id==null || employee ==null){
            throw new BusinessException("非法参数");
        }
        employee.setId(id);
        int count = employeeMapper.updateByPrimaryKey(employee);
        if(count==0){
            throw new BusinessException("更新失败");
        }
        //删除关系
        employeeMapper.deleteRoleRelationByEId(id);
        List<Long> roleIds = vo.getRoleIds();
        if(roleIds!=null && roleIds.size()>0){
            //插入新的关系
            employeeMapper.insertRoleRelationBatch(employee.getId(),roleIds);
        }

    }

    @Override
    public void delete(Long id) {
        int count = employeeMapper.deleteByPrimaryKey(id);
        if(count==0){
            throw new BusinessException("删除失败");
        }
        employeeMapper.deleteRoleRelationByEId(id);
    }

    @Override
    public void updateAdminState(Long id, Boolean admin) {
        employeeMapper.updateAdminState(id,admin);
    }

    @Override
    public Employee getByNameAndPassword(String name, String password) {
        return employeeMapper.getByNameAndPassword(name,password);
    }
}
